# This is a sample Python script.

# Press ⌃R to execute it or replace it with your code.
# Press Double ⇧ to search everywhere for classes, files, tool windows, actions, and settings.

import cv2 as cv
import numpy as np


def get_desc(path, orb):
    gray = cv.imread(path, cv.IMREAD_GRAYSCALE)
    kp, des = orb.detectAndCompute(gray, None)
    out = cv.drawKeypoints(gray, kp, None, color=(0, 255, 0), flags=0)
    # out = cv.drawKeypoints(gray, kp, gray, flags=cv.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)
    return gray, out, kp, des


icon_path = '/Users/wanggh/Desktop/icon.png'
original_path = '/Users/wanggh/Desktop/original.jpeg'
orb = cv.ORB_create()

icon_src, icon_out, icon_kp, icon_des = get_desc(icon_path, orb)
# original_src, original_out, original_kp, original_des = get_desc(original_path, orb)

# index_params = dict(algorithm=1,
#                     table_number=6,  # 12
#                     key_size=12,  # 20
#                     multi_probe_level=1)
# search_params = dict(checks=50)
# flann = cv.FlannBasedMatcher(index_params, search_params)
# matches = flann.knnMatch(icon_des, original_des, k=2)
#
# good = []
# for m, n in matches:
#     if m.distance <= 0.7 * n.distance:
#         good.append(m)
# # 单应性
# if len(good) > 10:
#     # 改变数组的表现形式，不改变数据内容，数据内容是每个关键点的坐标位置
#     src_pts = np.float32([icon_kp[m.queryIdx].pt for m in good]).reshape(-1, 1, 2)
#     dst_pts = np.float32([original_kp[m.trainIdx].pt for m in good]).reshape(-1, 1, 2)
#     # findHomography 函数是计算变换矩阵
#     # 参数cv2.RANSAC是使用RANSAC算法寻找一个最佳单应性矩阵H，即返回值M
#     # 返回值：M 为变换矩阵，mask是掩模
#     M, mask = cv.findHomography(src_pts, dst_pts, cv.RANSAC, 5.0)
#     # ravel方法将数据降维处理，最后并转换成列表格式
#     matchesMask = mask.ravel().tolist()
#     # 获取img1的图像尺寸
#     h, w, dim = icon_src.shape
#     # pts是图像img1的四个顶点
#     pts = np.float32([[0, 0], [0, h - 1], [w - 1, h - 1], [w - 1, 0]]).reshape(-1, 1, 2)
#     # 计算变换后的四个顶点坐标位置
#     dst = cv.perspectiveTransform(pts, M)
#     # 根据四个顶点坐标位置在img2图像画出变换后的边框
#     img2 = cv.polylines(original_src, [np.int32(dst)], True, (0, 0, 255), 3, cv2.LINE_AA)
# else:
#     print("Not enough matches are found - %d/%d") % (len(good), 10)
#     matchesMask = None

cv.imshow('icon_out', icon_out)
cv.waitKey(0)
cv.destroyAllWindows()
